#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <iostream>

using namespace std;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindowClass)
{
    ui->setupUi(this);
    timer = new QTimer(this);
    ui->qwtPlot->setAutoReplot(true);
    ui->qwtPlot_2->setAutoReplot(true);
    ui->qwtPlot_3->setAutoReplot(true);
    ui->qwtPlot->setAxisTitle(0, "Aceleracion");
    ui->qwtPlot_2->setAxisTitle(0, "Velocidad");
    ui->qwtPlot_3->setAxisTitle(0, "Posicion");

    for(int i=0; i < 20000; i++)
    {
        ejeX[i] = i;
    }

    QActionGroup *group = new QActionGroup(ui->mainToolBar);
    this->x = new QAction("X", group);
    this->x->setCheckable(true);
    this->y = new QAction("Y", group);
    this->y->setCheckable(true);
    this->z = new QAction("Z", group);
    this->z->setCheckable(true);
    this->parar = new QAction("Parar", group);
    this->parar->setCheckable(true);
    ui->mainToolBar->addAction(this->x);
    ui->mainToolBar->addAction(this->y);
    ui->mainToolBar->addAction(this->z);
    ui->mainToolBar->addAction(this->parar);

    connect(this->x, SIGNAL(triggered()), this, SLOT(graficar()));
    connect(this->y, SIGNAL(triggered()), this, SLOT(graficar()));
    connect(this->z, SIGNAL(triggered()), this, SLOT(graficar()));
    connect(this->parar, SIGNAL(triggered()), this, SLOT(pararTimer()));
}

void MainWindow::pararTimer()
{
    if(timer->isActive())
    {
        timer->stop();
        buffer.stopThread();
    }
}

void MainWindow::graficar()
{
    ui->statusBar->showMessage("Calibrando... por favor espere...", 3200);
    if(timer->isActive())
    {
        timer->stop();
    }
    ui->qwtPlot->clear();
    ui->qwtPlot_2->clear();
    ui->qwtPlot_3->clear();

    if(this->x->isChecked())
    {
        buffer.initialize('x');
    }
    else if(this->y->isChecked())
    {
        buffer.initialize('y');
    }
    else if(this->z->isChecked())
    {
        buffer.initialize('z');
    }
    buffer.start();
    connect(timer, SIGNAL(timeout()), this, SLOT(generarGraficos()));
    timer->start(50);
}

void MainWindow::generarGraficos()
{
    int size = ui->spinBox->value();

    double* y = buffer.vectorAceleracion();
    double* y2 = buffer.vectorVelocidad();
    double* y3 = buffer.vectorPosicion();

    ui->qwtPlot->clear();
    ui->qwtPlot_2->clear();
    ui->qwtPlot_3->clear();

    curve1 = new QwtPlotCurve();
    curve1->setData(ejeX, y, size);
    curve1->attach(ui->qwtPlot);
    curve2 = new QwtPlotCurve();
    curve2->setData(ejeX, y2, size);
    curve2->setPen(QPen(Qt::blue));
    curve2->attach(ui->qwtPlot_2);
    curve3 = new QwtPlotCurve();
    curve3->setData(ejeX, y3, size);
    curve3->setPen(QPen(Qt::red));
    curve3->attach(ui->qwtPlot_3);
}

MainWindow::~MainWindow()
{
    delete ui;
}
